package com.baohulu.baohulu.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.baohulu.baohulu.R;
import com.baohulu.baohulu.base.BaseActivity;
import com.baohulu.baohulu.base.BaseResponseCallback;
import com.baohulu.baohulu.bean.UserRecord;
import com.baohulu.baohulu.utils.HttpUtil;
import com.baohulu.baohulu.utils.JsonUtil;
import com.baohulu.baohulu.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 展示用户租借记录的界面
 */
public class RecordActivity extends BaseActivity {
    private static final String TAG = "RecordActivity";

    @BindView(R.id.user_record)
    RecyclerView mRvUserRecord;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private int page = 1;
    private UserRecordAdapter mUserRecordAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);
        ButterKnife.bind(this);
        initRefreshLayout();
        initRecyclerView();
        getUserRecord();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setEnableAutoLoadmore(false);
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                getUserRecord();
            }
        });
    }

    private void getUserRecord() {
        JSONObject data = new JsonUtil.JsonBuilder()
                .put("page", page)
                .build();
        String url = getString(R.string.url_base) + getString(R.string.url_get_user_record);
        HttpUtil.post(this, url, data, new BaseResponseCallback() {
            @Override
            public void onStart() {
                showProgressDialog();
            }

            @Override
            public void onJsonObjectResponse(JSONObject jsonObject) {
                super.onJsonObjectResponse(jsonObject);
                try {
                    int state = jsonObject.getInt("state");
                    if (state == 1) {
                        JSONArray jsonArray = jsonObject.getJSONArray("records");
                        if (jsonArray.length() == 0) {
                            ToastUtil.showToast(R.string.no_more_records);
                        } else {
                            List<UserRecord> userRecords = new ArrayList<>();
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject object = jsonArray.getJSONObject(i);
                                UserRecord record = UserRecord.fromJsonObject(object);
                                userRecords.add(record);
                            }
                            mUserRecordAdapter.addRecords(userRecords);
                            //页码加1
                            page++;
                        }
                    } else {
                        Log.e(TAG, "onJsonObjectResponse: 获取用户记录state=0");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "onJsonObjectResponse: ", e);
                } finally {
                    hideProgressDialog();
                    mRefreshLayout.finishLoadmore();
                }
            }

            @Override
            public void onCanceled() {
                super.onCanceled();
                hideProgressDialog();
                Log.i(TAG, "onCanceled: ");
            }

            @Override
            public void onFailure(String msg) {
                hideProgressDialog();
                Log.e(TAG, "onFailure: " + msg);
            }
        });
    }

    private void initRecyclerView() {
        mRvUserRecord.setLayoutManager(new LinearLayoutManager(this));
        mUserRecordAdapter = new UserRecordAdapter();
        mRvUserRecord.setAdapter(mUserRecordAdapter);
    }

    class UserRecordAdapter extends RecyclerView.Adapter<UserRecordAdapter.ViewHolder> {
        private List<UserRecord> mUserRecords;

        UserRecordAdapter() {
            mUserRecords = new ArrayList<>();
        }

        void addRecords(List<UserRecord> records) {
            mUserRecords.addAll(records);
            notifyDataSetChanged();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(RecordActivity.this)
                    .inflate(R.layout.item_user_record, parent, false);
            return new ViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            UserRecord record = mUserRecords.get(position);
            holder.tvStartTime.setText(record.getStartTime());
            holder.tvRentTime.setText(record.getRentTime());
            String cost = String.format(Locale.getDefault(), getString(R.string.price_format), record.getCost());
            holder.tvCost.setText(cost);
        }

        @Override
        public int getItemCount() {
            return mUserRecords.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            private TextView tvStartTime;
            private TextView tvRentTime;
            private TextView tvCost;

            ViewHolder(View itemView) {
                super(itemView);
                tvStartTime = itemView.findViewById(R.id.record_start_time);
                tvRentTime = itemView.findViewById(R.id.record_rent_time);
                tvCost = itemView.findViewById(R.id.record_cost);
            }
        }
    }
}
